package ru.pb.game.network.clients;

import java.awt.Color;

import ru.pb.game.dao.PlayerDAO;
import ru.pb.game.network.engine.client.packets.sendable.PROTOCOL_BASE_GET_CHANNELLIST_ACK;
import ru.pb.game.objects.model.players.Player;
import ru.pb.game.objects.model.players.enums.RANK;
import ru.pb.global.dao.DAOManager;
import ru.pb.global.network.MacAddr;
import ru.pb.global.network.engine.NioClient;
import ru.pb.global.network.engine.NioService;
import ru.pb.global.network.engine.NioSession;
import ru.pb.global.network.engine.core.interfaces.IPacketExecutor;

/**
 * Клиент игры или сам игрок.
 * 
 * @author Felixx
 */
public class GameClient extends NioClient<GameClient>
{
	private static PlayerDAO _dao = DAOManager.getDAOImpl(PlayerDAO.class);
	private MacAddr _mac;
	private String _account;
	private byte[] _localip;
	private Player _player;
	private int _channelId = -1;

	@SuppressWarnings("rawtypes")
	public GameClient(NioSession<GameClient> session, NioService service, IPacketExecutor executor)
	{
		super(session, service, executor);
	}

	@Override
	public void onStart()
	{
		sendPacket(new PROTOCOL_BASE_GET_CHANNELLIST_ACK());
	}

	@Override
	public void onEnd()
	{
		if(_player != null)
		{
			_player.logout(false, false, false);
		}
	}

	@Override
	public void onForceEnd()
	{
		if(_player != null)
		{
			_player.logout(false, false, false);
		}
	}

	@Override
	public void catchException(Throwable cases)
	{
		_log.info("Exception: " + cases);
	}

	@Override
	public int getId()
	{
		return hashCode() / 4096;
	}

	@Override
	public int getCryptKey()
	{
		return 29890;
	}

	@Override
	public void setMAC(MacAddr mac)
	{
		_mac = mac;
	}

	@Override
	public MacAddr getMac()
	{
		return _mac;
	}

	public void setAccount(String acc)
	{
		_account = acc;
	}

	public String getAccount()
	{
		return _account;
	}

	public void setPlayer(Player p)
	{
		_player = p;
		if(p != null)
		{
			_player.setClient(this);
		}
	}

	public void setChannelId(int id)
	{
		_channelId = id;
	}

	public int getChannelId()
	{
		return _channelId;
	}

	public Player getPlayer()
	{
		return _player;
	}

	public Player restorePlayer(String acc)
	{
		Player player = _dao.select(acc);
		if(player != null)
		{
			player.setConnected(true);
			if(RANK.valueOf(player.getPlayerInfos().getRank()) == RANK.RANK_GAMEMASTER)
			{
				Color col = Color.pink;
				_log.info("SET color: " + col.getRGB());
				player.getPlayerInfos().setFakeNameColor(col);
			}
			setPlayer(player);
		}
		return player;
	}

	public void setLocalIp(byte[] ip)
	{
		_localip = ip;
	}

	public byte[] getLocalIp()
	{
		return _localip;
	}
}